// Drools 测试平台 JavaScript

// 全局配置
const API_BASE_URL = '';
const LOADING_MODAL = new bootstrap.Modal(document.getElementById('loadingModal'));

// 工具函数
function showLoading() {
    console.log('显示加载弹窗');
    LOADING_MODAL.show();
}

function hideLoading() {
    console.log('隐藏加载弹窗');
    LOADING_MODAL.hide();
}

function formatJSON(obj) {
    return JSON.stringify(obj, null, 2)
        .replace(/("[\w]+"):/g, '<span class="json-key">$1</span>:')
        .replace(/: (".*?")/g, ': <span class="json-string">$1</span>')
        .replace(/: (\d+\.?\d*)/g, ': <span class="json-number">$1</span>')
        .replace(/: (true|false)/g, ': <span class="json-boolean">$1</span>');
}

function displayResult(containerId, data, isSuccess = true) {
    const container = document.getElementById(containerId);
    const statusClass = isSuccess ? 'result-success' : 'result-error';
    const statusIndicator = isSuccess ? 'status-success' : 'status-error';
    
    if (typeof data === 'string') {
        container.innerHTML = `
            <div class="${statusClass}">
                <span class="${statusIndicator} status-indicator"></span>
                <strong>${isSuccess ? '成功' : '错误'}:</strong><br>
                ${data}
            </div>
        `;
    } else {
        container.innerHTML = `
            <div class="${statusClass}">
                <span class="${statusIndicator} status-indicator"></span>
                <strong>${isSuccess ? '响应结果' : '错误信息'}:</strong><br>
                <div class="json-result">${formatJSON(data)}</div>
            </div>
        `;
    }
}

function makeRequest(url, data, resultContainerId) {
    showLoading();
    
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        displayResult(resultContainerId, data, true);
    })
    .catch(error => {
        console.error('请求失败:', error);
        displayResult(resultContainerId, error.message, false);
    })
    .finally(() => {
        hideLoading();
    });
}

// 个性化推荐
document.getElementById('recommendForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = {
        userId: document.getElementById('userId').value,
        segments: document.getElementById('segments').value.split(','),
        age: parseInt(document.getElementById('age').value),
        region: document.getElementById('region').value,
        channel: document.getElementById('channel').value,
        page: document.getElementById('page').value,
        engagementScore: parseInt(document.getElementById('engagementScore').value)
    };
    
    makeRequest('/api/recommend', formData, 'recommendResult');
});

// 风控评估
document.getElementById('riskForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = {
        userId: document.getElementById('riskUserId').value,
        creditScore: parseInt(document.getElementById('creditScore').value),
        income: parseFloat(document.getElementById('income').value),
        loanAmount: parseFloat(document.getElementById('loanAmount').value),
        hasCollateral: document.getElementById('hasCollateral').value === 'true',
        employmentYears: parseInt(document.getElementById('employmentYears').value)
    };
    
    makeRequest('/api/risk/assess', formData, 'riskResult');
});

// 定价计算
document.getElementById('pricingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = {
        productId: document.getElementById('productId').value,
        basePrice: parseFloat(document.getElementById('basePrice').value),
        customerLevel: document.getElementById('customerLevel').value,
        quantity: parseInt(document.getElementById('quantity').value),
        season: document.getElementById('season').value,
        region: document.getElementById('region').value
    };
    
    makeRequest('/api/pricing/calculate', formData, 'pricingResult');
});

// 快速测试用例填充函数

// 个性化推荐测试用例
function fillRecommendVIP() {
    document.getElementById('userId').value = 'vip001';
    document.getElementById('segments').value = 'VIP';
    document.getElementById('age').value = '35';
    document.getElementById('region').value = '上海';
    document.getElementById('channel').value = 'mobile';
    document.getElementById('page').value = 'homepage';
    document.getElementById('engagementScore').value = '92';
}

function fillRecommendNew() {
    document.getElementById('userId').value = 'new001';
    document.getElementById('segments').value = '新用户';
    document.getElementById('age').value = '22';
    document.getElementById('region').value = '深圳';
    document.getElementById('channel').value = 'web';
    document.getElementById('page').value = 'homepage';
    document.getElementById('engagementScore').value = '78';
}

function fillRecommendLowScore() {
    document.getElementById('userId').value = 'user001';
    document.getElementById('segments').value = '普通用户';
    document.getElementById('age').value = '28';
    document.getElementById('region').value = '广州';
    document.getElementById('channel').value = 'wechat';
    document.getElementById('page').value = 'homepage';
    document.getElementById('engagementScore').value = '35';
}

// 风控评估测试用例
function fillRiskHigh() {
    document.getElementById('riskUserId').value = 'risk_high_001';
    document.getElementById('creditScore').value = '450';
    document.getElementById('income').value = '3000';
    document.getElementById('loanAmount').value = '500000';
    document.getElementById('hasCollateral').value = 'false';
    document.getElementById('employmentYears').value = '0.5';
}

function fillRiskMedium() {
    document.getElementById('riskUserId').value = 'risk_medium_001';
    document.getElementById('creditScore').value = '650';
    document.getElementById('income').value = '8000';
    document.getElementById('loanAmount').value = '200000';
    document.getElementById('hasCollateral').value = 'false';
    document.getElementById('employmentYears').value = '2';
}

function fillRiskLow() {
    document.getElementById('riskUserId').value = 'risk_low_001';
    document.getElementById('creditScore').value = '800';
    document.getElementById('income').value = '25000';
    document.getElementById('loanAmount').value = '100000';
    document.getElementById('hasCollateral').value = 'true';
    document.getElementById('employmentYears').value = '8';
}

// 定价计算测试用例
function fillPricingGold() {
    document.getElementById('productId').value = 'GOLD_PROD';
    document.getElementById('basePrice').value = '2000';
    document.getElementById('customerLevel').value = 'GOLD';
    document.getElementById('quantity').value = '5';
    document.getElementById('season').value = 'SPRING';
    document.getElementById('region').value = '华东';
}

function fillPricingBulk() {
    document.getElementById('productId').value = 'BULK_PROD';
    document.getElementById('basePrice').value = '500';
    document.getElementById('customerLevel').value = 'SILVER';
    document.getElementById('quantity').value = '100';
    document.getElementById('season').value = 'SUMMER';
    document.getElementById('region').value = '华南';
}

function fillPricingSeason() {
    document.getElementById('productId').value = 'SEASON_PROD';
    document.getElementById('basePrice').value = '1500';
    document.getElementById('customerLevel').value = 'BRONZE';
    document.getElementById('quantity').value = '20';
    document.getElementById('season').value = 'WINTER';
    document.getElementById('region').value = '华北';
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('Drools 测试平台已加载');
    
    // 添加表单验证提示
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const inputs = form.querySelectorAll('input[required], select[required]');
            let isValid = true;
            
            inputs.forEach(input => {
                if (!input.value.trim()) {
                    input.classList.add('is-invalid');
                    isValid = false;
                } else {
                    input.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                alert('请填写所有必填字段');
            }
        });
    });
    
    // 添加输入框焦点效果
    const inputs = document.querySelectorAll('.form-control, .form-select');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.parentElement.classList.add('focused');
        });
        
        input.addEventListener('blur', function() {
            this.parentElement.classList.remove('focused');
        });
    });
});

// 键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + Enter 提交当前聚焦的表单
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        const activeElement = document.activeElement;
        const form = activeElement.closest('form');
        if (form) {
            e.preventDefault();
            form.dispatchEvent(new Event('submit'));
        }
    }
    
    // Esc 键清空所有结果
    if (e.key === 'Escape') {
        const resultAreas = document.querySelectorAll('.result-area');
        resultAreas.forEach(area => {
            area.innerHTML = '';
            area.className = 'result-area';
        });
    }
});

// 导出功能（可选）
function exportResults() {
    const results = {
        timestamp: new Date().toISOString(),
        recommendation: document.getElementById('recommendResult').textContent,
        risk: document.getElementById('riskResult').textContent,
        pricing: document.getElementById('pricingResult').textContent
    };
    
    const dataStr = JSON.stringify(results, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `drools-test-results-${new Date().getTime()}.json`;
    link.click();
    
    URL.revokeObjectURL(url);
}